package captcha

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"my_gin_open/model"
	"my_go_open/utils"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func Check(code, cookie, ip, n string, l int) (re bool, msg string, err error) {
	code = utils.StrTrim(strings.ToLower(code))
	if len(code) != l {
		msg = "code length should be " + strconv.Itoa(l)
		return
	}
	cookieData, _ := url.ParseQuery(cookie)
	var timeThat int64
	if timeArr, ok := cookieData["time"]; !ok {
		msg = "wrong cookie, no [time] found"
		return
	} else if timeThat, err = strconv.ParseInt(timeArr[0], 10, 64); err != nil {
		msg = "wrong cookie, [time] err"
		return
	} else {
		timeNow := time.Now().Unix()
		if timeNow <= timeThat || timeNow-timeThat > 300 {
			msg = "wrong cookie: it is expired"
			return
		}
	}
	var codeSign string
	if signArr, ok := cookieData["sign"]; !ok {
		msg = "wrong cookie, no [sign] found"
		return
	} else {
		codeSign = signArr[0]
		if sign := fmt.Sprintf("%s%s%d%s", code, model.AppKey, timeThat, ip); utils.StrMd5(sign) != codeSign {
			msg = "wrong code"
			return
		}
	}
	rc := model.RedisPool.Get()
	defer func(rc redis.Conn) {
		_ = rc.Close()
	}(rc)
	if bln, _ := utils.RedisSet(rc, fmt.Sprintf("captcha:%s:%s", n, codeSign), "1", 300*time.Second, "NX"); !bln {
		msg = "it is an used code"
		return
	}
	re = true
	return
}
